package qst.com.bacK.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import qst.com.bacK.Constant;
import qst.com.bacK.utils.RequestUtil;
import qst.com.bacK.utils.WebUtil;
import qst.com.bacK.exception.ExamException;
import qst.com.bacK.pojo.entity.*;
import qst.com.bacK.question.QuestionHelper;
import qst.com.bacK.question.QuestionQueryParam;
import qst.com.bacK.service.AssessmentService;
import qst.com.bacK.service.DimensionService;
import qst.com.bacK.service.QuestionService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Author:   msh
 * Date:     2024/10/11 下午9:14
 * Description:
 */

@Controller
@RequestMapping("/question")
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private DimensionService dimensionService;
    @Autowired
    private AssessmentService assessmentService;

    //删除
    @RequestMapping("/delete.action")
    public void deleteQuestion(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        Question q = questionService.findById(id);
        try {
            questionService.deleteById(id);
            req.getSession().setAttribute("_message_key", "题目已删除");
        } catch (ExamException ex) {
            req.getSession().setAttribute("_error_key", ex.getMessage());
        }
        String url = "/question/list.action?assessmentId=" + q.getAssessmentId() + "&status="
                + q.getStatus() + "&type=" + q.getType();
        resp.sendRedirect(url);
    }

    //编辑或保存
    @RequestMapping("/dimension.action")
    public void dimension(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String method = RequestUtil.getString(req, "method");

        if ("save".equals(method)) {
            int qid = RequestUtil.getInt(req, "id");
            if (qid == 0) {
                qid = RequestUtil.getInt(req, "qid");
            }
            int[] pids = RequestUtil.getIntArray(req, "pid");
            if (pids == null) {
                Question question = questionService.findById(qid);
                List<PersonalityDimension> dimensionList = dimensionService.findDimensionByAssessment(question.getAssessmentId());
                req.setAttribute("dimensionList", dimensionList);
                List<Integer> attachedDimension = questionService.findDimensionIdByQuestion(qid);
                for (PersonalityDimension p : dimensionList) {
                    p.getExtras().put("checked", attachedDimension.contains(p.getId()) ? "checked" : "");
                }
                req.setAttribute("error", "你还未关联任何维度！");
                req.setAttribute("qid", qid);
                WebUtil.forward(req, resp, "/question/dimension.jsp");
            }
            questionService.attachDimension(qid, pids);
            resp.sendRedirect("/question/view.action?id=" + qid);
        } else {
            int id = RequestUtil.getInt(req, "id");
            Question question = questionService.findById(id);
            req.setAttribute("question", question);
            List<PersonalityDimension> dimensionList = dimensionService.findDimensionByAssessment(question.getAssessmentId());
            req.setAttribute("dimensionList", dimensionList);
            List<Integer> attachedDimension = questionService.findDimensionIdByQuestion(id);
            for (PersonalityDimension p : dimensionList) {
                p.getExtras().put("checked", attachedDimension.contains(p.getId()) ? "checked" : "");
            }
            WebUtil.forward(req, resp, "/question/dimension.jsp");
        }
    }

    // 编辑
    @RequestMapping("/edit.action")
    public void editQuestion(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Question question = questionService.findById(RequestUtil.getInt(req, "id"));
        List<Choice> choices = questionService.findChoices(question.getId());
        AssessmentType assessment = assessmentService.findAssessmentById(question.getAssessmentId());
        req.setAttribute("assessment", assessment);
        req.setAttribute("question", question);
        req.setAttribute("choices", choices);
        WebUtil.forward(req, resp, "/question/edit.jsp");
    }

    @RequestMapping("/list.action")
    public void listQuestion(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String submitButton = RequestUtil.getString(req, "create");

        if (submitButton.isEmpty())// 添加操作
        {
            List<AssessmentType> assessmentList = assessmentService.findAllAssessment();
            req.setAttribute("assessmentList", assessmentList);

            QuestionQueryParam param = QuestionQueryParam.create(req);
            req.setAttribute("query", param);
            List<Question> questionList = questionService.find(param);
            req.setAttribute("questionList", questionList);
            WebUtil.forward(req, resp, "/question/list.jsp");
        } else {
            QuestionQueryParam param = QuestionQueryParam.create(req);
            req.setAttribute("assessment",
                    assessmentService.findAssessmentById(param.getAssessmentId()));
            Question question = new Question();
            question.setType(param.getType());
            question.setDifficulty(4);
            req.setAttribute("question", question);
            WebUtil.forward(req, resp, "/question/create.jsp");
        }
    }

    // 保存
    @RequestMapping("/save.action")
    public void saveQuestion(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Question question = QuestionHelper.createQuestion(req);
        List<Choice> choices = QuestionHelper.createChoice(req);
        try {
            // todo 完成登陆后更改此处为当前用户
            User currentUser = (User) req.getSession().getAttribute(Constant.CURRENT_USER);
            question.setUserId(currentUser.getId());
            questionService.save(question, choices);
            req.getSession().setAttribute("_message_key", "试题保存到数据库中");
            resp.sendRedirect("/question/dimension.action?id=" + question.getId());
        } catch (ExamException ex) {
            req.getSession().setAttribute("_error_key", ex.getMessage());
            req.setAttribute("question", question);
            req.setAttribute("choices", choices);
            req.setAttribute("assessment", assessmentService.findAssessmentById(question.getAssessmentId()));
            WebUtil.forward(req, resp, "/question/create.jsp");
        }
    }

    // 更新
    @RequestMapping("/update.action")
    public void updateQuestion(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Question question = QuestionHelper.createQuestion(req);
        List<Choice> choices = QuestionHelper.createChoice(req);
        try {
            // todo 完成登陆后更改此处为当前用户
            User currentUser = (User) req.getSession().getAttribute(Constant.CURRENT_USER);
            question.setUserId(currentUser.getId());
            questionService.update(question, choices);
            req.getSession().setAttribute("_message_key", "试题已经保存到数据库中,请关联知识点");
            resp.sendRedirect("/question/dimension.action?method=show&id=" + question.getId());

        } catch (ExamException ex) {
            req.getSession().setAttribute("_error_key", ex.getMessage());
            req.setAttribute("question", question);
            req.setAttribute("choices", choices);
            req.setAttribute("assessment", assessmentService.findAssessmentById(question.getAssessmentId()));
            WebUtil.forward(req, resp, "/question/edit.jsp");
        }
    }

    // view
    @RequestMapping("/view.action")
    public void viewQuestion(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Question question = questionService.findById(RequestUtil.getInt(req, "id"));
        List<Choice> choices = questionService.findChoices(question.getId());
        AssessmentType assessment = assessmentService.findAssessmentById(question.getAssessmentId());
        List<PersonalityDimension> dimension = questionService.findDimensionByQuestion(question.getId());
        req.setAttribute("assessment", assessment);
        req.setAttribute("question", question);
        req.setAttribute("choices", choices);
        req.setAttribute("dimension", dimension);

        WebUtil.forward(req, resp, "/question/view.jsp");
    }
}